#!/usr/bin/env python
# -*- coding: utf-8 -*-

from twisted.internet.protocol import Factory, Protocol
import re
from config import config

class MJPEG_Protocol(Protocol):
    def __init__(self):
        self.Process = None
        self.conf = config()
        
    def connectionMade(self):
        self.im_id = None

    def dataReceived(self, data):
        #print "Server said:", data
        data_ln = data.strip().split("\r\n", 5)
        n = len(self.conf.cameras)
        result = re.search(r"GET /(\d+) HTTP/1.1", data_ln[0])
        if result and int(result.group(1)) < n:
            self.im_id = int(result.group(1))
        elif data_ln[0] == "GET /index.html HTTP/1.1" or data_ln[0] == "GET / HTTP/1.1":
            html = """HTTP/1.1 200 OK\r
Server: CamProxy\r
Content-Type: text/html; charset=windows-1251\r
Connection: close\r
\r
<html>\r
<head>\r
<title>CamProxy</title>\r
</head>\r
<body>\r
<h1>CamProxy</h1>\r<br>
CamProxy is a proxy application that takes several MJPEG streams over RTSP, resizes them and transfers further over HTTP.<br>\r
List of streams:<br>\r"""
            for index, camera in enumerate(self.conf.cameras):
                html += '\r\n<a href="/%d">Camera %s</a><br>\r\n' % (index, camera['name'])
            html += """
<br>\r
Created by Sergey Lalov&copy; 2011<br>\r
</body>\r
</html>\r
"""
            self.transport.write(html)
            self.transport.loseConnection()
        else:
            self.transport.write("""HTTP/1.1 200 OK\r
Server: CamProxy\r
Content-Type: text/html; charset=windows-1251\r
Connection: close\r
\r
<html>\r
<head>\r
<title>CamProxy: Not Found</title>\r
</head>\r
<body>\r
<b>Error 404</b><br><br>The requested page is not found on this server.\r
</body>\r
</html>\r
""")
            self.transport.loseConnection()

        if self.im_id is not None:
            self.transport.write("""HTTP/1.0 200 OK
Connection: close\r
Server: CamProxy/0.1\r
Cache-Control: no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0\r
Pragma: no-cache\r
Expires: Mon, 3 Jan 2000 12:34:56 GMT\r
Content-Type: multipart/x-mixed-replace;boundary=boundarydonotcross\r
\r
""")
            self.factory.Process.connect(self.im_id, self.transport)

    def connectionLost(self, reason):
        if self.im_id is not None:
            self.factory.Process.disconnect(self.im_id)
            self.im_id = None

class MJPEG_Factory(Factory):
    protocol = MJPEG_Protocol
    def __init__(self, CamproxyProcess):
        self.Process = CamproxyProcess